

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Island
 */
@WebServlet("/Island")
public class Island extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    public Island() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession ses = request.getSession();
		Database data = null;
		Integer USER_ID = null;
		Integer P_ADDRESS = null;
		Integer urlAddress = null;
		ResultSet poz = null;
		if(ses.getAttribute("USER_ID")==null){
			response.sendRedirect("Login");
			return;
		} else {
			USER_ID = (Integer) ses.getAttribute("USER_ID");
		}
		P_ADDRESS = (Integer) ses.getAttribute("P_ADDRESS");
		if(P_ADDRESS == null){
			response.sendRedirect("Overview");
			return;
		}
		if(request.getParameter("address") != null){
			urlAddress = Integer.parseInt(request.getParameter("address"));
		}
		
		if(urlAddress == null){
			urlAddress = P_ADDRESS / 10;
		}
		ArrayList<Integer> uID = new ArrayList<>();
		ArrayList<Integer> pAdd = new ArrayList<>();
		ArrayList<Integer> pSize = new ArrayList<>();
		ArrayList<String> uName = new ArrayList<>();
		try {
			data = new Database();
			poz = data.Select("*").From("PLAYER_POSITION").Where("P_ADDRESS BETWEEN " + (urlAddress*10)+" AND "+(urlAddress*10+9)).OrderBy("P_ADDRESS").GetResult();
			while(poz.next()){
				uID.add(poz.getInt("USER_ID"));
				pAdd.add(poz.getInt("P_ADDRESS"));
				pSize.add(poz.getInt("P_SIZE"));
			}
			Iterator<Integer> iter = uID.iterator();
			ResultSet res = null;
			data.Close();
			while(iter.hasNext()){
				int id = iter.next();
				data = new Database();
				res = data.Select("NAME").From("G_USER").Where("USER_ID = " + id).GetResult();
				res.next();
				uName.add(res.getString("NAME"));
				data.Close();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		request.setAttribute("Island", urlAddress);
		request.setAttribute("USERS", uID);
		request.setAttribute("Addresses", pAdd);
		request.setAttribute("Size", pSize);
		request.setAttribute("UserName", uName);
		request.getRequestDispatcher("Island.jsp").forward(request, response);
		return;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
